<template>
  <MainFrame />
  <div class="shoppingcrad">
    <div class="car_head">
      <div class="car_logo">
      </div>
      <div class="car_search">
        <div class="search">
          <input class="input"
                 placeholder="请输入商品"
                 type="text" />
          <button>搜索</button>
        </div>
      </div>
    </div>
    <div class="car_content">
      <el-table ref="shoppingCarRef"
                :data="arr"
                style="width: 100%"
                @selection-change="selectionChange">
        <el-table-column type="selection"
                         width="180" />
        <el-table-column label="商品"
                         width="180">
          <template #default="scope">
            <el-image :src="scope.row.goodsImgurl"
                      :fit="fit"
                      style="width:100%" />
          </template>
        </el-table-column>
        <el-table-column label="名称"
                         prop="goodsName"
                         width="180" />
        <el-table-column label="价格"
                         prop="goodsPrice,goodsNum"
                         width="180">
          <template #default="scope">
            {{ scope.row.goodsPrice*scope.row.goodsNum }}
          </template>
        </el-table-column>
        <el-table-column label="数量">
          <template #default="scope">
            <el-input-number v-model="scope.row.goodsNum"
                             :min="1"></el-input-number>
          </template>
        </el-table-column>
        <el-table-column min-width="180">
          <template #header>
          </template>
          <template #default="scope">
            <el-button size="small"
                       type="danger"
                       @click.prevent="handleDelete(scope.$index)">删除</el-button>
          </template>

        </el-table-column>
      </el-table>
    </div>
  </div>
  <div class="content_bottom">
    <p class="fr check-num"><span>{{ getTotal.totalNum }}</span>件商品总计（不含运费）：{{ getTotal.totalPrice }}</p>
    <el-button type="danger"
               plain
               @click="handleclear()">清空</el-button>
    <el-button type="danger"
               plain
               @click="handledel()">删除</el-button>
    <el-button type="success"
               @click="handlpay()"
               plain>购买</el-button>
  </div>
</template>

<script>
import { ElMessage } from 'element-plus'
import MainFrame from '../views/MainFrame.vue'
export default {
  name: 'ShoppingCardView',
  components: {
    MainFrame,
  },
  data() {
    return {
      arr: [
        {
          name: '桂圆红枣茶',
          price: 35,
          url: require('../assets/goods/CHALI/guiyuanhongzhaocha_white.jpg'),
          num: 2,
        },
        {
          name: '红豆薏米茶',
          price: 35,
          url: require('../assets/goods/CHALI/hongdouyimicha_white.jpg'),
          num: 2,
        },
        {
          name: '蜜桃乌龙茶',
          price: 35,
          url: require('../assets/goods/CHALI/mitaowulong_white.jpg'),
          num: 2,
        },
        {
          name: '雪梨白茶',
          price: 35,
          url: require('../assets/goods/CHALI/xuelibaicha_white.jpg'),
          num: 2,
        },
      ],
    }
  },
  computed: {
    // 计算总数量及价格
    getTotal() {
      var totalNum = 0
      var totalPrice = 0
      for (let i = 0; i < this.arr.length; i++) {
        totalNum += this.arr[i].goodsNum
        totalPrice += this.arr[i].goodsPrice * this.arr[i].goodsNum
      }
      return {
        totalNum: totalNum,
        totalPrice: totalPrice,
      }
    },
  },
  methods: {
    // 多选信息
    shoppingCarRef() {
      console.log(multipleSelection.value)
    },
    // 被选商品列表
    selectionChange(val) {
      console.log(val)
      this.selectList = val
    },
    // 删除选择列表
    handledel() {
      console.log(this.selectList)
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          //遍历获得多选选中的index值
          this.selectList.forEach((value, index) => {
            //遍历多选框获取的数据
            this.arr.forEach((v, i) => {
              //遍历数据表，任意一个属性值相同，则说明该数据被选中，其i则为索引值
              if (value.goodsName == v.goodsName) {
                this.arr.splice(i, 1)
              }
            })
          })
          this.$message({
            type: 'success',
            message: '删除成功!',
          })
          console.log('删除成功')
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
    // 根据index删除商品
    handleDelete(index) {
      console.log(index)
      this.$store.commit('delToCar', index)
      console.log(this.$store.state.car)
      ElMessage({
        message: '移除成功！',
        type: 'success',
      })
    },
    // 清空购物车列表
    handleclear() {
      this.arr = []
      this.$store.state.car = []
      localStorage.setItem('car', [])
      ElMessage({
        message: '清空成功！',
        type: 'success',
      })
    },
    //多选购买商品
    handlpay() {
      console.log(this.selectList)
      console.log(this.$store.state.user.username)
      console.log('查看用户状态' + this.user.userId)
      var good_id = new Array()
      var og_num = new Array()
      for (let i = 0; i < this.selectList.length; i++) {
        good_id[i] = this.selectList[i].goodsOutId
        og_num[i] = this.selectList[i].goodsNum
      }
      console.log('商品id' + good_id + '商品数量' + og_num)
      this.$http
        .post('/addOrders', {
          user_id: this.user.userId,
          good_id: good_id, // 商品id数组
          order_price: parseFloat(good_id),
          og_price: parseFloat(og_num),
          og_num: og_num, // 商品数量数组
        })
        .then((success) => {
          console.log(success.data)
          this.selectList.forEach((value, index) => {
            //遍历多选框获取的数据
            this.arr.forEach((v, i) => {
              //遍历数据表，任意一个属性值相同，则说明该数据被选中，其i则为索引值
              if (value.goodsName == v.goodsName) {
                this.arr.splice(i, 1)
              }
            })
          })
          ElMessage({
            message: success.data,
            type: 'success',
          })
        })
    },
  },

  created() {
    console.log(this.$store.state.car)
    this.arr = this.$store.state.car
    let username = this.$store.state.user.username
    // 获取用户信息
    this.$http({
      url: '/getOneUser',
      method: 'GET',
      params: {
        username: username,
      },
    }).then((success) => {
      console.log(success.data)
      this.user = success.data
    })
  },
}
</script>

<style lang="scss">
.car_head {
  width: 100%;
  display: flex;
  /* background-color: bisque; */
}
.car_logo {
  width: 30%;
}
.car_search {
  padding-top: 50px;
  margin-right: 5%;
  width: 60%;
  display: flex;
  justify-content: flex-end;
  /* 通过border-radius样式设置搜索框的圆角属性 */
}
.search {
  width: 750px;
  height: 42px;
  background-color: white;
  border-radius: 16px;
  padding: 2px;
  border: 2px rgb(235, 197, 198) solid;
  display: flex;
  justify-content: flex-end;
}
.car_search input {
  margin: 2px;
  padding-left: 20px;
  width: 80%;
  height: 36px;
  border: none;
  outline: none;
  border-radius: 16px;
  font-size: 16px;
}
.car_search button {
  width: 20%;
  /* height: 36px; */
  border-radius: 16px;
  border: none;
  font-weight: 800;
  font-size: 24px;
  background: radial-gradient(rgba(235, 197, 198, 1), rgba(235, 197, 198, 1));
  color: #ffff;
}
.car_content {
  width: 80%;
  // height: 1300px;
  background-color: #f4f4f4;
  margin: 0 auto;
  border-radius: 24px;
}
.shopcar_item {
  width: 100%;
  padding-top: 5%;
  padding-left: 10%;
  display: flex;
  justify-content: flex-start;
  .img {
    width: 200px;
  }
}
.content_bottom {
  margin-top: 50px;
  button {
    margin: 10px;
    padding: 10px 20px;
  }
}
</style>